﻿using System;
using DeepMixWorkflow;
using Microsoft.Phone.BackgroundAudio;
using Silverlight.Media;

namespace DeepmixStreamAgent
{
    /// <summary>
    ///   A background agent that performs per-track streaming for playback
    /// </summary>
    public class AudioTrackStreamer : AudioStreamingAgent
    {
        private ShoutcastMediaStreamSource _bufferedMediaStreamSource;

        public AudioTrackStreamer()
        {
            CommonHelper.Log("Создан экземпляр AudioStreamer");
        }
        
        protected override void OnBeginStreaming(AudioTrack track, AudioStreamer streamer)
        {
            if (track.Tag != null)
            {
                string uriString;
                DeepMixMode deepMixMode = track.Tag.GetDeepMixMode(out uriString);
                switch (deepMixMode)
                {
                    case DeepMixMode.OnAir:
                        uriString = StorageContainer.ServerAddress.Value;
                        break;
                    case DeepMixMode.Selected:
                        //uristring уже задан
                        break;
                    default:
                        return; //все остальное не умеем читать
                }

                CommonHelper.Log("Вызван AudioStreamer.OnBeginStreaming:" + track.Tag);
                var uri = new Uri(uriString);

                _bufferedMediaStreamSource = new ShoutcastMediaStreamSource(uri);
                /*_bufferedMediaStreamSource.Closed += (sender, args) =>
                    {
                        CommonHelper.Log(
                            "Вызываем исключение, так как поток передал ошибку");
                        //throw new OpenMediaFailedException();
                        CommonHelper.SayErrcommor();
                    };*/
                _bufferedMediaStreamSource.Closed += (sender, args) => NotifyComplete();
                streamer.SetSource(_bufferedMediaStreamSource);
            }
        }

        protected override void OnCancel()
        {
            CommonHelper.Log("Вызван onCancel стримера");
            NotifyComplete();
        }
    }
}